#!/bin/php
<?php

if(empty($argv[1])) {
	echo "FAILURE: Please provide a JID as a first parameter!\n";
	exit;
}

$jid = $argv[1];
list($node, $domain) = explode('@', $jid);

if(empty($jid) || empty($domain)) {
	echo "FAILURE: Parameter JID must be in format node@domain !\n";
	exit;
}

require_once 'hostmetaxrd.class.php';
$raw_host_meta_data = get_url_content('http://' . $domain . '/.well-known/host-meta');
$hostmetaXRD = HostMetaXRD::buildFromRawXML($raw_host_meta_data);

//Because the specification says so and it makes sence.
if($hostmetaXRD->getHost() != $domain) {
	echo "FAILURE: User's domain (" . $domain . ") does not match to the host variable (" . $hostmetaXRD->getHost() . ") provided by host-meta file at 'http://" . $domain . "/.well-known/host-meta'!\n";
	exit;
}

require_once 'lrddxrd.class.php';
$raw_lrddxrd_data = get_url_content(HostMetaXRD::generateUserXrdURL($jid, $hostmetaXRD->getLrddTemplate()));
$lrddXRD = LRDDXRD::buildFromRawXML($raw_lrddxrd_data);

$updatesFrom = $lrddXRD->getLinkUpdatesFrom();
$salmonreplies = $lrddXRD->getLinkSalmonReplies();
$magicPublicKeyLink = $lrddXRD->getLinkMagicPublicKey();

// We still miss the hub URL
$raw_atomfeed_data = get_url_content($updatesFrom['href']);

require_once 'atomfeedparser.php';
$atomfeed = AtomFeedParser::buildFromRawXML($raw_atomfeed_data);
$hublink = $atomfeed->getLinkHub();

if(empty($hublink)) {
    echo "FAILURE: No hub link to the feed. Cannot subscribe!\n";
    exit;
}

debug("Want to subscribe to '" . $updatesFrom['href'] . "'?");
debug(" - hub             : '" . $hublink['href'] . "'.");
debug(" - Salmon Replies  : '" . $salmonreplies['href'] . "'.");
debug(" - Magic Public Key: '" . $magicPublicKeyLink['href'] . "'.");
debug("---------------------------");
debug("Done");

function get_url_content($url, $debug = true) {
	$ctx = stream_context_create(array(
    		'http' => array(
    			'method'=>'GET',
                'timeout' => 3
                )
            )
	    );

    debug("Ready to call url '$url'");
    $received_data = @file_get_contents($url, 0, $ctx);
    debug("Received '$received_data'.");
    return $received_data;
}

function debug($debug) {
	echo "\t" . $debug . "\n";
}

echo "OK";
echo "\n";